package com.lxq.market.servlet.update;

import com.google.gson.JsonObject;
import com.lxq.market.model.User;
import com.lxq.market.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@WebServlet("/update/update_user")
public class UpdateUserServlet extends HttpServlet {

    UserService userService=UserService.getInstance();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getParameter("action");
        JsonObject jsonObject=new JsonObject();
        actionStrategy(action,req,jsonObject);
        resp.setContentType("application/json;charset=utf-8");
        resp.getOutputStream().write(jsonObject.toString().getBytes(StandardCharsets.UTF_8));
    }

    private void actionStrategy(String action,HttpServletRequest req,JsonObject jsonObject){
        if (action==null){
            jsonObject.addProperty("result",false);
            return;
        }
        if (action.equals("")){
            jsonObject.addProperty("result",false);
            return;
        }
        switch (action){
            case "update":update(req,jsonObject);break;
            case "add":
                jsonObject.addProperty("result",false);
                jsonObject.addProperty("msg","未开通该功能");
                break;
            case "delete":delete(req,jsonObject);break;
            default:jsonObject.addProperty("result",false);
        }
    }

    private void update(HttpServletRequest req, JsonObject jsonObject) {
        String updateUserName = req.getParameter("update_user_name");
        String updateUserPosition = req.getParameter("update_user_position");
        String updateUserPassword = req.getParameter("update_user_password");
        String updateUserAccount = req.getParameter("update_user_account");
        User user=new User();
        user.setUserAccount(updateUserAccount);
        user.setUserPassword(updateUserPassword);
        user.setUserName(updateUserName);
        user.setUserPosition(updateUserPosition);
        boolean result = userService.updateUserInfoForAdmin(user);
        jsonObject.addProperty("result",result);
    }
    private void delete(HttpServletRequest req, JsonObject jsonObject) {
        String delUserAccount = req.getParameter("del_user_account");
        boolean delete = userService.delete(delUserAccount);
        jsonObject.addProperty("result",delete);
    }
}
